package com.code.view.listeners;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;

import com.code.view.ViewUtils;
import com.code.view.entity.TableItemControl;


/**
 * 删除按钮事件监听类
 *
 *
 * @author 朱国军
 * @version 2015年3月5日 朱国军
 */
public class DeleteMouseListener implements MouseListener {
    private Table table;

    private Shell shell;

    private Hashtable<TableItem, TableItemControl> tableControls;


    /**
     * 构造函数
     *
     * @param table 表格
     * @param shell 显示页面
     * @param tableControls 表格控件
     */
    public DeleteMouseListener(Table table, Shell shell, Hashtable<TableItem, TableItemControl> tableControls) {
        this.table = table;
        this.shell = shell;
        this.tableControls = tableControls;
    }


    @Override
    public void mouseUp(MouseEvent arg0) {
        // 储存删除索引的list
        List<Integer> indexs = new ArrayList<Integer>();
        for (int i = 0; i < table.getItemCount(); i++) {
            TableItem item = table.getItem(i);
            TableItemControl controls = tableControls.get(item);
            if (controls != null && controls.getCheckButton().getSelection()) {
                controls.dispose();
                tableControls.remove(item);
                indexs.add(i);
            }
        }
        int idx[] = new int[indexs.size()];
        for (int i = 0; i < indexs.size(); i++) {
            idx[i] = indexs.get(i);
        }

        // 删除对应index的表的item
        if (indexs.size() > 0) {
            table.remove(idx);
            table.pack(true);
            if (shell.getBounds().height > (table.getBounds().y + table.getItemCount() * 21 + 45 - 21 + 87)) {
                table.setSize(table.computeSize(shell.getBounds().width - 60, SWT.DEFAULT, true));
            } else {
                table.setSize(table.computeSize(shell.getBounds().width - 60, shell.getBounds().height - table.getBounds().y - 87 - 21,
                    true));
            }
        } else {
            MessageDialog messageDialog =
                    new MessageDialog(shell, "警告", ViewUtils.getImage("codegenerator.bmp"), "请勾选要删除的行", MessageDialog.WARNING,
                        new String[] { "确定" }, 1);
            messageDialog.open();
        }
    }


    @Override
    public void mouseDown(MouseEvent arg0) {

    }


    @Override
    public void mouseDoubleClick(MouseEvent arg0) {

    }
}
